package com.fenxiangle.yueding.feature.mine.view;


import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.common.widget.dialog.ActionSheetDialog;
import com.fenxiangle.yueding.common.widget.dialog.OnOperItemClickL;
import com.fenxiangle.yueding.common.widget.popupwindow.PopupWindowList;
import com.fenxiangle.yueding.entity.bo.EventEntity;
import com.fenxiangle.yueding.entity.bo.TabEntity;
import com.fenxiangle.yueding.entity.bo.UserCenterBo;
import com.fenxiangle.yueding.feature.focus.view.ExtendCoreActivity;
import com.fenxiangle.yueding.feature.focus.view.IdentificationActivity;
import com.fenxiangle.yueding.feature.focus.view.MeAccountActivity;
import com.fenxiangle.yueding.feature.login.view.LoginActivity;
import com.fenxiangle.yueding.feature.mine.contract.MineContract;
import com.fenxiangle.yueding.feature.mine.dependencies.mine.DaggerMineComponent;
import com.fenxiangle.yueding.feature.mine.dependencies.mine.MinePresenterModule;
import com.fenxiangle.yueding.feature.order.view.OrderActivity;
import com.fenxiangle.yueding.feature.publish.view.MyPublishActivity;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.luck.picture.lib.rxbus2.ThreadMode;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;


public class MyFragment extends BaseFragment implements OnOperItemClickL, MineContract.View {

    @BindView(R.id.iv_mine_head)
    ImageView ivMineHead;
    @BindView(R.id.tl_6)
    CommonTabLayout tl6;
    Unbinder unbinder;
    @BindView(R.id.btn_mine_certification)
    TextView btnMineCertification;
    @BindView(R.id.tv_user_name)
    TextView mTvUserName;
    @BindView(R.id.tv_user_id)
    TextView mTvUserId;
    @BindView(R.id.iv_user_sex)
    ImageView mIvUserSex;
    @BindView(R.id.tv_user_age)
    TextView mTvUserAge;
    @BindView(R.id.tv_user_certification_type)
    TextView mTvUserCertificationType;
    @BindView(R.id.tv_user_certification_position)
    TextView mTvUserCertificationPosition;
    @BindView(R.id.tv_user_address)
    TextView mTvUserAddress;
    @BindView(R.id.tv_user_time)
    TextView mTvUserTime;
    @BindView(R.id.tv_user_score)
    TextView mTvUserScore;
    @BindView(R.id.tv_user_comment)
    TextView mTvUserComment;
    Unbinder unbinder1;
    @BindView(R.id.tv_user_fans)
    TextView mTvUserFans;
    @BindView(R.id.btn_mine_account)
    TextView mBtnMineAccount;
    @BindView(R.id.btn_mine_order)
    TextView mBtnMineOrder;
    @BindView(R.id.btn_mine_publish)
    TextView mBtnMinePublish;
    @BindView(R.id.btn_mine_promote)
    TextView mBtnMinePromote;
    @BindView(R.id.rv_my_vedio)
    RecyclerView mRvMyVedio;
    @BindView(R.id.rv_my_photo)
    RecyclerView mRvMyPhoto;
    @BindView(R.id.scorll)
    NestedScrollView mScrollView;
    private ActionSheetDialog dialog;
    private String[] mTitles = {"视频", "照片"};
    private ArrayList<CustomTabEntity> mTabEntities;

    private ArrayList<Fragment> mFragments;

    private List<LocalMedia> selectList;
    private String uri;
    UserCenterBo mUserData;
    @Inject
    MineContract.Presenter mPresenter;

    private int mSelectTab = 0;

    @Override
    public int attachLayoutRes() {
        return R.layout.fragment_my;
    }

    @Override
    protected void initInjector() {
        DaggerMineComponent.builder().minePresenterModule(new MinePresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        AM.image().bindToCircleObject(R.drawable.iv_user_head, ivMineHead);


        final String[] stringItems = {"拍照", "从手机相册选择"};
        dialog = new ActionSheetDialog(getActivity(), stringItems, null);
        dialog.isTitleShow(false);
        dialog.setOnOperItemClickL(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        RxBus.getDefault().register(this);

        if (AM.user().isLogin()) {
            mPresenter.getUserData();
        } else {
            showUserData(null);
            Intent outIntent = new Intent(getActivity(),
                    LoginActivity.class);
            outIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                    | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(outIntent);
            getActivity().finish();
        }
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {
        tl6.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mSelectTab = position;
            }

            @Override
            public void onTabReselect(int position) {
                mSelectTab = position;
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBus(EventEntity obj) {
        switch (obj.what) {
            case 8:
                String mContent = obj.medias;
                if (!TextUtils.isEmpty(mContent)) {
                    mPresenter.getUserData();

                }
                break;

            case 999:
                String mContents = obj.medias;
                if (!TextUtils.isEmpty(mContents) && mContents.equals("a")) {
                    mPresenter.getUserData();
                }
                break;


            case 888:
                String mContentsw = obj.medias;
                if (!TextUtils.isEmpty(mContentsw) && mContentsw.equals("a")) {
                    mPresenter.getUserData();
                    if (tl6 != null) {
                        tl6.setCurrentTab(1);
                    }
                }
                break;
        }
    }

    @OnClick({R.id.iv_mine_head, R.id.btrn_mine_more, R.id.btrn_mine_setting,
            R.id.tv_user_name,
            R.id.btn_mine_account, R.id.btn_mine_certification,

            R.id.btn_mine_order, R.id.btn_mine_publish, R.id.btn_mine_promote})
    public void onViewClicked(View view) {
        if (!AM.user().isLogin()) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            return;
        }
        switch (view.getId()) {
            case R.id.iv_mine_head:
                if (dialog != null) dialog.show();
                break;
            case R.id.btrn_mine_more:
                break;
            case R.id.btrn_mine_setting:
                Intent intent = new Intent(getActivity(), SeetingActivity.class);
                intent.putExtra("id", mUserData.getBindingUserUid());
                intent.putExtra("time_value", mUserData.getTimeValue());
                startActivity(intent);
                break;
            case R.id.tv_user_name:
                Intent intents = new Intent(getActivity(), EditNickActivity.class);
                intents.putExtra("name", mTvUserName.getText().toString());
                startActivity(intents);
                break;
            case R.id.btn_mine_account:
                startActivity(new Intent(getActivity(), MeAccountActivity.class));
                break;
            case R.id.btn_mine_certification:
                PopupWindowList popupWindowList = new PopupWindowList(getActivity());
                popupWindowList.showMoreWindow(btnMineCertification, "身份认证", "老板认证", new PopupWindowList.PopupWindowListener() {
                    @Override
                    public void first() {
                        Intent intent = new Intent(getActivity(), IdentificationActivity.class);
                        intent.putExtra("type", "2");
                        startActivity(intent);
                    }

                    @Override
                    public void second() {
                        Intent intent = new Intent(getActivity(), IdentificationActivity.class);
                        intent.putExtra("type", "1");
                        startActivity(intent);


                    }
                });

                break;
            case R.id.btn_mine_order:
                startActivity(new Intent(getActivity(), OrderActivity.class));
                break;
            case R.id.btn_mine_publish:
                startActivity(new Intent(getActivity(), MyPublishActivity.class));
                break;
            case R.id.btn_mine_promote:
                startActivity(new Intent(getActivity(), ExtendCoreActivity.class));
                break;
        }
    }


    @Override
    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0:
                PictureSelector.create(this)
                        .openCamera(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style1)
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                        .previewImage(true)// 是否可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .enableCrop(true)// 是否裁剪
                        .compress(true)// 是否压缩
                        .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                        .isGif(false)// 是否显示gif图片
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .circleDimmedLayer(true)// 是否圆形裁剪
                        .selectionMedia(selectList)// 是否传入已选图片
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case 1:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style1)
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                        .previewImage(true)// 是否可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .isCamera(false)
                        .enableCrop(true)// 是否裁剪
                        .compress(true)// 是否压缩
                        .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                        .isGif(false)// 是否显示gif图片
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .circleDimmedLayer(true)// 是否圆形裁剪
                        .selectionMedia(selectList)// 是否传入已选图片
                        .scaleEnabled(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;

        }

        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < selectList.size(); i++) {
                        uri = selectList.get(i).getCutPath();
                    }
                    mPresenter.uploadUserHead(uri);
                    break;
            }
        }
    }


    @Override
    public void showUserDataSuccess(UserCenterBo userCenterBo) {
        mUserData = userCenterBo;
        showUserData(mUserData);
    }

    @Override
    public void showUploadHeadSuccess(String url) {
        showMsg("上传成功！");
        mPresenter.getUserData();
    }

    @Override
    public void showFollowSuccess() {

    }

    @Override
    public void showUnFollowSuccess() {

    }

    @Override
    public void showError(String error) {
        showMsg(error);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }

    private void showUserData(UserCenterBo userCenterBo) {

        if (AM.user().isLogin()) {
            if (userCenterBo == null) return;

            String membershipLevel = "无认证";

            if (userCenterBo.getBasicAuthentication().equals("1")) {
                membershipLevel = "已认证";
            }

            if (userCenterBo.getaManAuthentication().equals("1")) {
                membershipLevel = "达人认证";
            }

            if (userCenterBo.getBossAuthentication().equals("1")) {
                membershipLevel = "老板认证";
            }
            mTvUserName.setText(TextUtils.isEmpty(userCenterBo.getUserName()) ? "" : userCenterBo.getUserName());
            mIvUserSex.setImageResource(userCenterBo.getSex() == 0 ? R.drawable.ic_man : R.drawable.ic_gender_women);
            mTvUserFans.setText("粉丝:" + userCenterBo.getFans());
            mTvUserAge.setText(userCenterBo.getAge() + "");
            mTvUserCertificationType.setText(membershipLevel);
            mTvUserCertificationPosition.setText(userCenterBo.getOccupation());
            mTvUserAddress.setText((TextUtils.isEmpty(userCenterBo.getCity()) ? "暂无地址" : userCenterBo.getCity())
                    + (TextUtils.isEmpty(userCenterBo.getDetailAddress()) ? "" : userCenterBo.getDetailAddress()));
            mTvUserTime.setText("时间值：" +"￥" + userCenterBo.getTimeValue() + "/小时");
            mTvUserScore.setText("信用分：" + userCenterBo.getCreditScore());
            mTvUserComment.setText("评分：" + userCenterBo.getAssess());

            AM.image().bindToCircleObject(userCenterBo.getUserHead(), ivMineHead);
            mTvUserId.setText("ID:" + userCenterBo.getUserUid());
            mTabEntities = new ArrayList<>();
            for (int i = 0; i < mTitles.length; i++) {
                mTabEntities.add(new TabEntity(mTitles[i]));
            }
            tl6.setTabData(mTabEntities);
            tl6.setOnTabSelectListener(new OnTabSelectListener() {
                @Override
                public void onTabSelect(int position) {
                    switch (position){
                        case 0:
                            mRvMyPhoto.setVisibility(View.GONE);
                            mRvMyVedio.setVisibility(View.VISIBLE);
                            break;
                        case 1:
                            mRvMyPhoto.setVisibility(View.VISIBLE);
                            mRvMyVedio.setVisibility(View.GONE);
                            break;
                    }
                }

                @Override
                public void onTabReselect(int position) {

                }
            });

        } else {

            mTvUserName.setText("未登录");
            mIvUserSex.setImageResource(R.drawable.ic_man);
            mTvUserFans.setText("粉丝:");
            mTvUserAge.setText("");
            mTvUserCertificationType.setText("");
            mTvUserCertificationPosition.setText("");
            mTvUserAddress.setText("");
            mTvUserTime.setText("时间值：");
            mTvUserScore.setText("信用分：");
            mTvUserComment.setText("评分：");

            AM.image().bindToCircleObject(R.drawable.bg_yuan, ivMineHead);
            mTvUserId.setText("ID:");

            mTabEntities = new ArrayList<>();
            mFragments = new ArrayList<>();
            for (int i = 0; i < mTitles.length; i++) {
                mTabEntities.add(new TabEntity(mTitles[i]));
            }
            tl6.setTabData(mTabEntities);

        }

        mScrollView.scrollTo(0,0);
    }

}

